package database

import (
	"strings"
	"unicode"

	"gitee.com/botaoshow/yuanxin/web/common/conf"

	"gorm.io/gen"
	"gorm.io/gorm"
)

// DaoGenerator 生成dao代码
// 默认输出路径为 eg:internal/repository
func DaoGenerator(outPath string) {
	// 初始化配置文件
	conf.InitConf("conf.yaml")
	// 初始化数据库连接
	InitMysql()
	defer CloseMysql()
	var gormdb *gorm.DB
	gormdb = Db
	g := gen.NewGenerator(gen.Config{
		OutPath: outPath,
		//Mode:          gen.WithoutContext | gen.WithDefaultQuery | gen.WithQueryInterface, // generate mode
		Mode:          gen.WithDefaultQuery | gen.WithQueryInterface, // generate mode
		FieldNullable: true,
	})
	g.WithJSONTagNameStrategy(func(columnName string) (tagContent string) {
		//snake 转 小驼峰
		return toLowerCamelCase(columnName)
	})
	//gormdb, _ := gorm.Open(mysql.Open("root:@(127.0.0.1:3306)/demo?charset=utf8mb4&parseTime=True&loc=Local"))
	g.UseDB(gormdb) // reuse your gorm db

	// Generate basic type-safe DAO API for struct `model.User` following conventions

	//g.ApplyBasic(
	// Generate struct `User` based on table `users`
	//g.GenerateModel("users"),

	// Generate struct `Employee` based on table `users`
	//g.GenerateModelAs("users", "Employee"),

	// Generate struct `User` based on table `users` and generating options
	//g.GenerateModel("users", gen.FieldIgnore("address"), gen.FieldType("id", "int64")),

	// Generate struct `Customer` based on table `customer` and generating options
	// customer table may have a tags column, it can be JSON type, gorm/gen tool can generate for your JSON data type
	//g.GenerateModel("customer", gen.FieldType("tags", "datatypes.JSON")),
	//)
	g.ApplyBasic(
		// Generate structs from all tables of current database
		g.GenerateAllTable()...,
	)
	// Generate the code
	g.Execute()
}
func toLowerCamelCase(s string) string {
	parts := strings.Split(s, "_")
	for i := 1; i < len(parts); i++ {
		if len(parts[i]) > 0 {
			runes := []rune(parts[i])
			runes[0] = unicode.ToUpper(runes[0])
			parts[i] = string(runes)
		}
	}
	return strings.Join(parts, "")
}
